var mainStatsTimeStamp = 0;

var xhrMainStats ;



function waitForMainStats()
{
  location.hash = "livefeed";

    var serverURL = '/dazzler/longpoller/';
 var dataToPost= {  'GameID':GameID,'pollType':'mainStats','mainStatsTimeStamp':mainStatsTimeStamp};

  xhrMainStats = $.ajax({
       type: 'post',
       url: serverURL,
       data: dataToPost,
       dataType: "json",
       async: true,
       cache: false,
       success: function(data)
       {

        populateMainStats(data.score,data.ballCommentary,data.teams);
         mainStatsTimeStamp = data.newTimeStamp;
         waitForMainStats();


       },
            error: function(XMLHttpRequest, textStatus, errorThrown){

                $("#pageheader").html("Error. Main Stats Long Poller has stop functioning. Will retry in 5 seconds.");
                setTimeout(
               
               'waitForMainStats()', /* Try again after.. */
                    "5000"); /* milliseconds (5 seconds) */
            }

    });

}

function MainStats()
{
    this.homeTeam = $("input[id='homeTeamName']").val();
    this.awayTeam = $("input[id='awayTeamName']").val();
    this.battingTeam=null;
    this.bowlingTeam=null;
    this.Innings=null;
    this.FirstInningsRuns=null;
    this.FirstInningsOvers=null;
    this.FirstInningsWickets=null;
    
    this.SecondInningsRuns=null;
    this.SecondInningsOvers=null;
    this.SecondInningsWickets=null;

    this.statString=null;

    this.roundNumber = function(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

    this.calculateFirstInningsRunRate = function()
    {
           if (parseFloat(this.FirstInningsRuns) > 0 && parseFloat(this.FirstInningsOvers) > 0)
          {
     var runRate = parseFloat(this.FirstInningsRuns)/ parseFloat(this.FirstInningsOvers);
       return this.roundNumber(runRate,2);
          }
          else
              {
                    return parseInt("0.0");
              }
    }

    this.calculateSecondInningsRunRate = function()
    {
      if (parseFloat(this.SecondInningsOvers) > 0 && parseFloat(this.SecondInningsRuns) > 0)
          {
        var runRate = parseFloat(this.SecondInningsRuns)/ parseFloat(this.SecondInningsOvers);
       return this.roundNumber(runRate,2);
          }
          else
              {
                  return parseInt("0.0");
              }


    }

    this.calculateRequiredRunRate = function()
    {
             if (parseFloat(this.SecondInningsOvers) > 0 && parseFloat(this.SecondInningsRuns) > 0)
          {
           var requiredRunRate = (parseFloat(this.FirstInningsRuns) - parseFloat(this.SecondInningsRuns))/(50 - parseFloat(this.SecondInningsOvers));
       return this.roundNumber(requiredRunRate,2);        
          }
          else
              {
               return parseInt("0.0");
              }

    }

    this.getFirstInningsBatTeam = function()
    {
           if (this.Innings == "1")
        {
          //  alert('yers');
       return this.battingTeam ;
        }
        else if (this.Innings == "2")
        {

        return this.bowlingTeam;
       }
       else
           {
          return this.homeTeam;
           }
    }


        this.getSecondInningsBatTeam = function()
    {
           if (this.Innings == "1")
        {
         
         return this.bowlingTeam;
        }
        else if (this.Innings == "2")
        {

         return this.battingTeam ;
       }
       else
           {
            return this.awayTeam;

           }
    }

    this.setMainStatBannner = function()
    {
    if (this.homeTeam = null || this.awayTeam == null)
        {
    this.homeTeam = $("input[id='homeTeamName']").val();
    this.awayTeam = $("input[id='awayTeamName']").val();        
        }

     if (this.Innings == "1")
        {
          //  alert('yers');
            this.statString= this.battingTeam + " (1st Inn) "+ this.FirstInningsRuns +"/"+this.FirstInningsWickets+ ", "+this.FirstInningsOvers+" overs. Run Rate: "+this.calculateFirstInningsRunRate();
            $("#matchScore").html(this.statString);
        }
        else if (this.Innings == "2")
        {
           
           this.statString= this.battingTeam + " (2nd Inn) "+ this.SecondInningsRuns +"/"+this.SecondInningsWickets+ ", "+this.SecondInningsOvers+" overs. Run Rate: "+this.calculateSecondInningsRunRate()+" Required Run Rate: "+ this.calculateRequiredRunRate()
            +"<br>"+this.bowlingTeam +"  (1st Inn) "+ this.FirstInningsRuns +"/"+this.FirstInningsWickets+ " after "+this.FirstInningsOvers+" overs.";
            $("#matchScore").html(this.statString);
       }
    }
}

function populateMainStats(score,ballCommentary,teams)
{

if ($('#nextmessage').is(':empty'))
    {
  $("#nextmessage").html(ballCommentary);
    }
    else
    {
$("#nextmessage").append("|   |"+ballCommentary);
    }

mainStatsObj.Innings = score.Innings;
mainStatsObj.battingTeam = teams.batting.TEAM_POOL_NAME;
mainStatsObj.bowlingTeam = teams.bowling.TEAM_POOL_NAME;

mainStatsObj.FirstInningsRuns = score.firstInnings.runs;
mainStatsObj.FirstInningsOvers = score.firstInnings.overs;
mainStatsObj.FirstInningsWickets = score.firstInnings.wickets;

mainStatsObj.SecondInningsRuns = score.secondInnings.runs;
mainStatsObj.SecondInningsOvers = score.secondInnings.overs;
mainStatsObj.SecondInningsWickets = score.secondInnings.wickets;
mainStatsObj.setMainStatBannner();

}